package com.googlecode.jerato.library.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.jerato.core.view.ViewFunction;
import com.googlecode.jerato.core.view.ViewParameters;
import com.googlecode.jerato.library.Settings;
import com.googlecode.jerato.library.SystemService;

public class ViewServlet extends HttpServlet{
	protected static int _systemInitializeCount = 0;
	protected Settings _viewSettings;
	protected ViewService _viewService = new ViewService();

	public void destroy() {
		_systemInitializeCount--;
		if(_systemInitializeCount == 0){
			SystemService.staticFinalize();
		}
		_viewService.shutdown();
		super.destroy();
	}

	public void init() throws ServletException {
		super.init();
		if(_systemInitializeCount == 0){
			ViewSystemService service = new ViewSystemService(getServletContext());
			SystemService.staticInitialize(service);
		}
		_systemInitializeCount++;
		_viewSettings = ViewSettings.getInstance();
		_viewService.startup();
	}

	public static final long serialVersionUID = ViewServlet.class.hashCode();

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String path = req.getServletPath();
		ViewFunction view = _viewService.getView(path);

		ViewParameters input = new ViewParametersImpl();
		ViewParameters output = new ViewParametersImpl();
		ViewTransferImpl trans = new ViewTransferImpl();

		for(Enumeration enumParam = req.getParameterNames(); enumParam.hasMoreElements(); ){
			String paramName = (String)enumParam.nextElement();
			input.put(paramName, req.getParameter(paramName));
		}
		ServletContext servletContext = getServletContext();
		trans.setServletContext(servletContext);

		view.call(trans, input, output);
		String buffer = trans.getStringBuffer();
		PrintWriter writer = null;
		try {
			writer = resp.getWriter();
			
			writer.write(buffer);
			writer.flush();
		}
		finally {
			if(writer != null){
				writer.close();
			}
		}
//		byte[] cache = input.getCacheData();
//		ServletOutputStream stream = null;
//		try {
//			stream = resp.getOutputStream();
//			
//			stream.write(cache);
//			stream.flush();
//		}
//		finally {
//			if(stream != null){
//				stream.close();
//			}
//		}
	}
	
}
